//
//  ZYXNetManager.m
//  ZYXApp
//
//  Created by 梁炜东 on 2017/4/20.
//  Copyright © 2017年 梁炜东. All rights reserved.
//

#import "ZYXNetManager.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"

static AFHTTPSessionManager *manager;

#define consumerKey @"iOS"

@interface ZYXNetManager ()
@property (nonatomic, copy) NSString *requestUrl;
@property (nonatomic, assign)  RequestType requestType;
@property (nonatomic, assign)  RequestSerializer requestSerializer;
@property (nonatomic, assign)  ResponseSerializer responseSerializer;
@property (nonatomic, assign)  Content_Type content_Type;
@property (nonatomic, strong)  NSData *imageData;//上传图片的图片流
@property (nonatomic, copy)  id parameters;
@property (nonatomic, assign) NSTimeInterval timeOut;
@property(nonatomic, copy)NSString *baseURL;
@end

@implementation ZYXNetManager
- (ZYXNetManager* (^)(NSString *baseUrl))bh_baseUrl
{
    return ^ZYXNetManager* (NSString *baseUrl)
    {
        self.baseURL = baseUrl;
        return self;
    };
}

- (ZYXNetManager* (^)(NSString *url))bh_requestUrl
{
    return ^ZYXNetManager* (NSString *url) {
        self.requestUrl = url;
        return self;
    };
}

- (ZYXNetManager* (^)(RequestType requestType))bh_requestType
{
    return ^ZYXNetManager* (RequestType requestType) {
        self.requestType = requestType;
        return self;
    };
}

- (ZYXNetManager* (^)(RequestSerializer serializer))bh_requestSerializer
{
    return ^ZYXNetManager* (RequestSerializer serializer) {
        self.requestSerializer = serializer;
        return self;
    };
}

- (ZYXNetManager* (^)(ResponseSerializer serializer))bh_responseSerializer
{
    return ^ZYXNetManager* (ResponseSerializer serializer) {
        self.responseSerializer = serializer;
        return self;
    };
}

- (ZYXNetManager* (^)(id parameters))bh_parameters
{
    return ^ZYXNetManager *(id parameters) {
        self.parameters = parameters;
        return self;
    };
}

- (ZYXNetManager * (^)(NSTimeInterval timeOut))bh_TimeOut
{
    return ^ZYXNetManager *(NSTimeInterval timeOut)
    {
        self.timeOut = timeOut;
        return self;
    };
}

- (ZYXNetManager* (^)(Content_Type content_Type))bh_ContentType
{
    return ^ZYXNetManager* (Content_Type content_Type) {
        self.content_Type = content_Type;
        return self;
    };
}

- (ZYXNetManager* (^)(NSData *imageData))bh_ImageData
{
    return ^ZYXNetManager* (NSData *imageData)
    {
        self.imageData = imageData;
        return self;
    };
}

/**
 *  获取BHNetReqManager单例并进行初始化设置
 *
 *  @return 返回BHNetReqManager
 */
+(instancetype)sharedManager
{
    static ZYXNetManager *sharedManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[ZYXNetManager alloc] init];
        [sharedManager resetConfigWithManager];
    });
    return sharedManager;
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BaseUrl] sessionConfiguration:configuration];
        manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
        manager.requestSerializer.timeoutInterval = 10.f;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript", @"text/plain",@"image/jpeg",@"image/png", @"application/octet-stream", nil];
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
        self.baseURL = BaseUrl;
    }
    return self;
}

/**
 *  请求方法/consumerKey/请求参数一起参数的加密运算，用于获取mac值
 *
 *
 *  @return 返回加密后的值，可与服务器端协商加密算法
 */
- (NSString *)sign
{
    NSString *sign = @"signTest";
    return sign;
}

/**
 *  配置请求体格式
 */
-(void)setupRequestSerializerWithManager
{
    switch (self.requestSerializer)
    {
        case HTTPRequestSerializer:
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            break;
        case JSONRequestSerializer:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case PropertyListRequestSerializer:
            manager.requestSerializer = [AFPropertyListRequestSerializer serializer];
            break;
        default:
            break;
    }
}

/**
 *  配置响应体格式
 */
-(void)setupResponseSerializerWithManager
{
    switch (self.responseSerializer)
    {
        case HTTPResponseSerializer:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case JSONResponseSerializer:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case XMLParserResponseSerializer:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
}

/**
 *  配置请求体Content_Type
 */
-(void)setupRequestContentTypeWithManager
{
    switch (self.content_Type)
    {
        case Form_urlencoded:
            [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            break;
        case form_data:
//            [manager.requestSerializer setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
            break;
        case JSON:
            
            break;
        case XML:
            
            break;
        default:
            break;
    }
}

/**
 *  对请求头体格式、响应体格式 超时  接受类型
 */
-(void)setupAFHTTPSessionManager
{
    [self setupRequestSerializerWithManager];
    [self setupResponseSerializerWithManager];
    [self setupRequestContentTypeWithManager];
    //    NSString *sessid = [[ZORequestSession shareSessionData] getSession];
    //    NSLog(@"sessid = %@", sessid);
//        [manager.requestSerializer setValue:sessid forHTTPHeaderField:@"sendsessid"];
    //    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    //    NSInteger num = [[defaults objectForKey:language] integerValue];
    //    NSString *strV = [NSString stringWithFormat:@"1-%ld-%@-1-1", num,clientVersion];
    //    [manager.requestSerializer setValue:strV forHTTPHeaderField:@"v"];//
    
}

-(void)startRequestWithCompleteHandler:(httpResult)handler
{
    [self setupAFHTTPSessionManager];
    manager.requestSerializer.timeoutInterval = self.timeOut;
    switch (self.requestType)
    {
        case GET:
        {
            NSString *url = nil;
            if (!self.requestUrl || [self.requestUrl isEqualToString:@""])
            {
                url = self.baseURL;
            }else
            {
                url = [NSString stringWithFormat:@"%@%@", self.baseURL, self.requestUrl];
            }
            [manager GET:url parameters:self.parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
             {
                 NSLog(@"responseObject = %@", responseObject);
//                 NSString *strHtml = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//                 [self checkstatus:handler responseObject:responseObject task:task];
                 handler(task, responseObject, nil);
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
             {
                 NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"NetworkErrors" forKey:NSLocalizedDescriptionKey];
                 error = [NSError errorWithDomain:BaseUrl code:error.code userInfo:userInfo];
                 handler(task, nil, error);
             }];
            break;
        }
        case POST:
        {
            NSString *url = [NSString stringWithFormat:@"%@%@", self.baseURL, self.requestUrl];
            [manager POST:url parameters:self.parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
             {
                 NSLog(@"responseObject = %@", responseObject);
                 handler(task, responseObject, nil);
                 //                [self checkstatus:handler responseObject:responseObject  task:task];
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
             {
                 NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"NetworkErrors" forKey:NSLocalizedDescriptionKey];
                 error = [NSError errorWithDomain:BaseUrl code:error.code userInfo:userInfo];
                 handler(task, nil, error);
             }];
            break;
        }
        default:
            break;
    }
    [self resetConfigWithManager];
}
//图片的上传
-(void)startImageUploadWithCompleteHandler:(httpResult)handler
{
    NSString *url = [NSString stringWithFormat:@"%@%@", self.baseURL, self.requestUrl];
    [manager POST:url parameters:self.parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
    {
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat =@"yyyyMMddHHmmss";
//        NSString *str = [formatter stringFromDate:[NSDate date]];
//        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:self.imageData
                                    name:@"img"
                                fileName:@"lwdUserImage"
                                mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress)
    {
        NSLog(@"");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        NSLog(@"");
        handler(task, responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        NSLog(@"");
        handler(task, nil, error);
    }];
    [self resetConfigWithManager];
}
////固件升级检查校验请求
//-(void)startRequestUpdateWithCompleteHandler:(httpResult)handler
//{
//    NSString *urlStr = [NSString stringWithFormat:@"%@%@", self.baseURL, self.requestUrl];
////    NSURL *url = [NSURL URLWithString:[self.requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//    NSURL *url = [NSURL URLWithString:urlStr];
////    NSData *body = (NSData *)self.parameters;
//    NSData *body = [NSJSONSerialization dataWithJSONObject:self.parameters options:NSJSONWritingPrettyPrinted error:nil];
//    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
//
//    [urlRequest setHTTPMethod:@"post"];
//    [urlRequest setHTTPBody:body];
//    [urlRequest setTimeoutInterval:30];
//    NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
//    [NSURLConnection sendAsynchronousRequest:urlRequest queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        if ([data length] > 0 && connectionError == nil)
//        {
//            dispatch_async(dispatch_get_main_queue(), ^
//                           {
//                               NSString *strHtml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//                               NSDictionary *dataDic = [NSDictionary parseJSONStringToNSDictionary:strHtml];
//                               NSLog(@"HTML = %@",strHtml);
//                               handler(nil, dataDic, nil);
//                           });
//        }else if ([data length] == 0 && connectionError == nil)
//        {
//            NSLog(@"Nothing was downloaded.");
//        }else if (connectionError != nil){
//
//            dispatch_async(dispatch_get_main_queue(), ^
//                           {
//                               handler(nil, nil, connectionError);
//                           });
//        }
//    }];
//    [self resetConfigWithManager];
//}

/**
 *  请求成功200的情况下 检查响应码
 *
 *  @param httpResult   block
 *  @param responseObject 响应体
 */
-(void)checkstatus:(httpResult)httpResult responseObject:(NSDictionary *)responseObject task:(NSURLSessionDataTask *)task
{
    NSInteger status = [responseObject[@"status"] integerValue];
    if (status == 1)
    {
        httpResult(task, responseObject, nil);
    }
    else
    {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"UnknownError" forKey:NSLocalizedDescriptionKey];
        //sessid过期 107  别的设备登录 106
        //        if (status == 107 || status == 100000011 || status == 110)
        //        {
        //            [ZOJPLoginTool removeAllLoginInfo];
        //            [ZOJPLoginTool setLogin:NO];
        //            userInfo = [NSDictionary dictionaryWithObject:@"LoginExpire" forKey:NSLocalizedDescriptionKey];
        //        }
        //        else if(status == 106)
        //        {
        //            [ZOJPLoginTool removeAllLoginInfo];
        //            [ZOJPLoginTool setLogin:NO];
        //            userInfo = [NSDictionary dictionaryWithObject:kString(@"LoginYourAccountIsOnOtherDevicesPleaseLoginAgain") forKey:NSLocalizedDescriptionKey];
        //        }
        //        else if(responseObject[@"tips"])
        //        {
        //            userInfo = [NSDictionary dictionaryWithObject:responseObject[@"tips"] forKey:NSLocalizedDescriptionKey];
        //        }
        NSError *error = [NSError errorWithDomain:BaseUrl code:status userInfo:userInfo];
        httpResult(task, responseObject, error);
    }
}

/**
 *  恢复默认设置
 */
-(void)resetConfigWithManager
{
    self.requestUrl = nil;
    self.requestType = GET;
    self.requestSerializer = JSONResponseSerializer;
    self.responseSerializer = JSONResponseSerializer;
    self.parameters = nil;
    self.timeOut = 10.f;
    self.content_Type = -1;
}

@end
